/*文章类型缓存Helper
  Create At 2017-12-20
*/
var AtTypeCache=(function(wx){
  var articleType = null;
  var articleTypeCacheName = "articleType";
  var wx=wx;
  var AtTypeCache = {
    /*从缓存中获取所有文章类型 */
    getAll: function () {
      /*
      wx.getStorage({
        key: articleTypeCacheName,
        success: function(res) {
          fn.call(this,res);
        },
      })
      */
      return wx.getStorageSync(articleTypeCacheName);
    },

    /*根据类型ID获取指定类型*/
    getByTypeId: function (targetId) {
      var atTypeList = wx.getStorageSync(articleTypeCacheName);
      console.log("缓存：", atTypeList);
      var targetType = _getType(targetId, atTypeList);
      return targetType;
    },
    
    /*设置文章缓存*/
    setCache: function (data) {
      try {
        
        /*
        wx.setStorage({
          key: articleTypeCacheName,
          data: data,
        });
        */
        wx.setStorageSync(articleTypeCacheName, data)
      }
      catch (e) {
        console.log("读取缓存【ArticleCache】出错：" + e.message);
      }
    }
  }



  /*递归获取指定文章类型对象*/
  function _getType(targetId, data) {
    var targetObj = null;

    if (data.length != undefined) {
      for (var obj in data) {
        var currentType;
        var item;
        var array;

        /*判断是数组或对象*/
        if (isNaN(obj) == false) {
          item = data[obj];
        }
        else {
          item = obj;
        }

        /*若找到对应对象，则返回上一级递归*/
        if (item.ID == targetId) {
          targetObj = item;
          return targetObj;
        }
        /*
        console.log(item.ID);
        console.log(item);
        */
        array = item.LineList;
        if (array == undefined) {
          array = item.Line;
        }
        /*递归继续查找*/
        if (array != undefined && array.length > 0) {
          targetObj = _getType(targetId, array);
        }

        /*返回匹配结果*/
        if (targetObj != null) {
          return targetObj;
        }
      }
      return targetObj;
    }
  }

  return AtTypeCache;

})(wx);




module.exports.AtTypeCache = AtTypeCache;